const express = require('express');
const router = express.Router();
const userMapper = require('../mapper/userMapper');
const userInfoMapper = require('../mapper/userInfoMapper');
const userAccountMapper = require('../mapper/userAccountMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');
const openidUtil = require('../utils/getOpenid');

router.post('/v1/user', (req, res) => {
  const { familyName, lastName, uAvatar, gender, tel, pswd, cardid, code } = req.body;
  conn.query(userAccountMapper.selectForRegisterCheck, [ tel ], (err, data) => {
    if(err) {
      return res.send({ code: 500, err });
    } if(data) {
      if (data[0].total > 0) {
        return res.send({ code: 400, err: '用户已存在' });
      }
      conn.query(userMapper.add, [ familyName, lastName, uAvatar, gender ], (err, data) => {
        if(err) {
          return res.send({ code: 500, err });
        } if(data) {
          conn.query(userInfoMapper.init, [data.insertId]);
          openidUtil(code).then(openid => {
            conn.query(userAccountMapper.add, [ data.insertId, tel, pswd, openid, cardid ])
            const token = jwt.generate(data.insertId);
            data.token = token;
            return res.send({ code: 200, data });
          });
        }
      });
    }
  });
});

router.get('/v1/user', (req, res) => {
  const { tel, pswd, code } = req.query;
  if(code) {
    return openidUtil(code).then(openid => {
      conn.query(userAccountMapper.selectForLogin, [ null, openid ], (err, result) => {
        if(err) {
          res.send({ code: 500, err });
        } if(result) {
          if(!result.length) {
            return res.send({ code: 401, err: "用户不存在" });
          }
          const id = result[0].id;
          conn.query(userMapper.selectFullUserInfo, [ id ], (err, data) => {
            if(err) {
              res.send({ code: 500, err });
            } if(data) {
              var user = data[0];
              user.id = id;
              user.token = jwt.generate(id);
              res.send({ code: 200, data: user });
            }
          });
        }
      });
    }).catch(err => {
      res.send({ code: 401, err });
    });
  } else {
    conn.query(userAccountMapper.selectForLogin, [ tel, null ], (err, result) => {
      if(err) {
        res.send({ code: 500, err });
      } if(result) {
        if(!result.length) {
          res.send({ code: 401, err: "用户不存在" });
        } else if(pswd == result[0].pswd) {
          const id = result[0].id;
          conn.query(userMapper.selectFullUserInfo, [ id ], (err, data) => {
            if(err) {
              res.send({ code: 500, err });
            } if(data) {
              var user = data[0];
              console.log(id);
              user.id = id;
              user.token = jwt.generate(id);
              res.send({ code: 200, data: user });
            }
          });
        } else {
          res.send({ code: 400, err: "密码错误" });
        }
      }
    });
  }
});

router.put('/v1/user', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  } 
  
  const { user, info, id } = req.body;
  const { familyName, lastName, gender } = user || {};
  const { contact, uSign, region, regionId } = info || {};
  if(validate != id) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }

  const udpateUser = () => {
    return new Promise((resolve, reject) => {
      conn.query(userMapper.update, [ familyName, lastName, gender, id ], (err, data) => {
        if(err) {
          reject(err);
        } if(data) {
          resolve(data);
        }
      });
    });
  }

  const updateInfo = () => {
    return new Promise((resolve, reject) => {
      conn.query(userInfoMapper.update, [ contact, uSign, region, regionId, id ], (err, data) => {
        if(err) {
          reject(err);
        } if(data) {
          resolve(data);
        }
      });
    });
  }

  console.log(user, info);
  if(user) {
    udpateUser().then(data => {
      if(info) {
        updateInfo().then(data => {
          res.send({ code: 200, data });
        }).catch(err => {
          res.send({ code: 500, err });
        });
      }
    }).catch(err => {
      res.send({ code: 500, err });
    })
  } else if(info) {
    updateInfo().then(data => {
      res.send({ code: 200, data });
    }).catch(err => {
      res.send({ code: 500, err });
    });
  }
});

module.exports = router;